package com.cpe.service.student;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.cpe.data.domain.member.Member;
import com.cpe.data.domain.student.Student;
import com.cpe.repository.mapper.member.MemberMapper;
import com.cpe.repository.mapper.student.StudentMapper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@Transactional
public class StudentService {

	@Resource
	private Environment environment;

	@Resource
	private StudentMapper studentMapper;

	@Resource
	private MemberMapper memberMapper;

	public void addOne(Student student, boolean sendSms) throws Exception {
		Assert.notNull(student);
		student.setCreateTime(new Date());
		student.setGroup("散户组");
		student.setClassId("未分班");
		// 生成唯一编号（时间戳）
		student.setSerialNumber(System.currentTimeMillis() + "");
		String mobile = student.getParentMobile();
		if (sendSms) {
			// 发送短信到家长手机上
			String host = environment.getProperty("yuntongxun.host");
			String port = environment.getProperty("yuntongxun.port");
			String accountSid = environment.getProperty("yuntongxun.account.sid");
			String authToken = environment.getProperty("yuntongxun.auth.token");
			String appid = environment.getProperty("yuntongxun.appid");
			String tmpl = environment.getProperty("yuntongxun.serailno.tmpl");
			CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
			restAPI.init(host, port);
			restAPI.setAccount(accountSid, authToken);
			restAPI.setAppId(appid);
			String[] datas = new String[] { student.getName(), student.getSerialNumber() };
			Map<String, Object> result = restAPI.sendTemplateSMS(mobile, tmpl, datas);
			if ("000000".equals(result.get("statusCode"))) {
				// 正常返回输出data包体信息（map）
				studentMapper.insert(student);
				// 关联家长
				Member member = memberMapper.findByMobile(mobile);
				if (member != null && member.getMobileStatus() == 1) {
					this.updateParent(student, member.getId());
				}
			} else {
				// 异常返回输出错误码和错误信息
				String message = "错误码=" + result.get("statusCode") + " 错误信息= " + result.get("statusMsg");
				log.info(message);
				throw new Exception(message);
			}
		} else {
			studentMapper.insert(student);
			// 关联家长
			Member member = memberMapper.findByMobile(mobile);
			if (member != null && member.getMobileStatus() == 1) {
				this.updateParent(student, member.getId());
			}
		}
	}

	/**
	 * 更新家长信息
	 */
	public void updateParent(Student student, String parentId) throws Exception {
		Assert.notNull(student);
		Assert.hasText(student.getId());
		student.setParentId(parentId);
		studentMapper.updateById(student);
	}
}
